/**********************************************
** @Des: This file ...
** @Author: haodaquan
** @Date:   2017-09-08 00:18:02
** @Last Modified by:   haodaquan
** @Last Modified time: 2017-09-16 17:26:48
***********************************************/

package models

import (
	"fmt"
	"strings"
	"strconv"
	"net/url"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

var (
	appHash            map[int]*SysApp
	payItemHash        map[int]*PayItem
	catList            []*SysCat
	tagList            []*SysTag
	configTopList      []*ConfigTopic
	configTempFreeList []*ConfigTempFree
	rankList           []*SysRnk
)

func Init() {
	// default
	registerDb("default")

	// admin
	registerDb("admin")
	orm.RegisterModel(new(Auth), new(Role), new(RoleAuth), new(Admin))

	if beego.AppConfig.String("runmode") == beego.DEV {
		orm.Debug = true
	}

	// 缓存表格数据
	// 应用表
	if list, err := GetAllSysApp(); err != nil {
		fmt.Println("get sys_app error.", err)
	} else {
		appHash = map[int]*SysApp{}
		for _, app := range list {
			appHash[app.Id] = app
		}
	}
	// 分类表
	if list, err := GetAllSysCat(); err == nil {
		catList = append(catList, list...)
	}
	// 标签表
	if list, err := GetAllTag(); err == nil {
		tagList = append(tagList, list...)
	}
	// 栏目配置表
	if list, err := GetAllConfigTopic(); err == nil {
		configTopList = append(configTopList, list...)
	}
	// 限时免费配置表
	if list, err := GetAllConfigTempFree(); err == nil {
		configTempFreeList = append(configTempFreeList, list...)
	}
	// 排行榜配置表
	if list, err := GetAllSysRnk(); err == nil {
		rankList = append(rankList, list...)
	}
	// 支付项目表
	if list, err := GetAllPayItem(); err == nil {
		payItemHash = map[int]*PayItem{}
		for _, pay := range list {
			payItemHash[pay.Id] = pay
		}
	}
}

func GetCatById(id int) *SysCat {
	for _, v := range catList {
		if v.Id == id {
			return v
		}
	}
	return nil
}

func GetCatByChannel(channel int8) []*SysCat {
	sysCats := make([]*SysCat, 0)
	for _, v := range catList {
		if v.ChannelType == channel {
			sysCats = append(sysCats, v)
		}
	}
	return sysCats
}

func GetTagsById(ids string) string {
	tagArr := make([]string, 0)
	idArr := strings.Split(ids, ",")
	for _, id := range idArr {
		for _, v := range tagList {
			if strconv.Itoa(v.Id) == id {
				tagArr = append(tagArr, v.TagName)
			}
		}
	}
	return strings.Join(tagArr, ",")
}

func TableName(name string) string {
	return name
}

func registerDb(name string) {
	dbhost := beego.AppConfig.String(name + ".host")
	dbport := beego.AppConfig.String(name + ".port")
	dbuser := beego.AppConfig.String(name + ".user")
	dbpassword := beego.AppConfig.String(name + ".password")
	dbname := beego.AppConfig.String(name + ".name")
	timezone := beego.AppConfig.String(name + ".timezone")
	if dbport == "" {
		dbport = "3306"
	}
	dsn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8"
	if timezone != "" {
		dsn = dsn + "&loc=" + url.QueryEscape(timezone)
	}
	orm.RegisterDataBase(name, "mysql", dsn)
}

func getAdminDb() orm.Ormer {
	db := orm.NewOrm()
	db.Using("admin")
	return db
}
